// import 'layui-src';
// layui.config({
//   dir: '/dist/'
// })
// import 'layui-src/src/css/layui.css';
// import 'layui-src/src/css/modules/laydate/default/laydate.css';
// import 'layui-src/src/css/modules/layer/default/layer.css';
// import 'layui-src/src/css/modules/code.css';

import '../../css/list.css';

import $ from "../jquery-3.4.1.min.js";
import "./index.js";
import ajax from "../../utils/ajsx.js";
const AnnouncementData = {
  count: 0,
  limit: 2,
  page: 1
}
const RepairData = {
  count: 0,
}
let danjia;
let tiaoshu;
const arr = [];
const data = [];
var selectData;
let dataLength;
var DecorateId = [];
var del = [];
const aboutMaintenance = {
  limit: 0,
  page: 0
}
//选项卡
layui.use('element', function () {
  var element = layui.element;

  //…
});
function renderForm() {
  layui.use('form', function () {
    var form = layui.form;
    form.render();
  });
}

layui.use('table', function () {
  var table = layui.table;

  table.render({
    elem: '#test'
    , url: '/demo/table/user/'
    , cols: [[
      { type: 'checkbox' }
      , { field: 'id', width: 80, title: 'ID', sort: true }
      , { field: 'username', width: 80, title: '用户名' }
      , { field: 'sex', width: 80, title: '性别', sort: true }
      , { field: 'city', width: 80, title: '城市' }
      , { field: 'sign', title: '签名', minWidth: 100 }
      , { field: 'experience', width: 80, title: '积分', sort: true }
      , { field: 'score', width: 80, title: '评分', sort: true }
      , { field: 'classify', width: 80, title: '职业' }
      , { field: 'wealth', width: 135, title: '财富', sort: true }
    ]]
    , page: true
  });
});

function showTr(data) {
  const trs = data.map(item => (
    `
      <tr>
          <td>${item.name}</td>
          <td>${item.ClassificationId.name}</td>
          <td>${item.communityId.name}</td>
          <td>${item.addTime}</td>
          <td>${item.type ? "已发布" : "草稿"}</td>
          <td>${item.userId ? item.userId.username : ""}</td>
          <td>${item.top ? "是" : "否"}</td>
          <td>
              <button class="layui-btn layui-btn-normal" data-val="${item._id}" id="up">编辑</button>
              <button class="layui-btn layui-btn-primary"  data-val="${item._id}" id="del" >删除</button>
          </td>
      </tr>
    `
  ))
  $("#list-content").html(trs);
}


async function tablePageShow() {
  var value = "";
  value = value.trim();
  let num = AnnouncementData.limit;
  let pag = AnnouncementData.page;
  const { code, data, countNum } = await ajax({ url: "Announcement/getAnnouncement", type: "get", data: { value, num, pag } });
  AnnouncementData.count = countNum.length;
  // console.log(countNum)
  //分页
  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    // console.log(AnnouncementData.count);
    //完整功能
    laypage.render({
      elem: 'demo7'
      , count: AnnouncementData.count
      , limit: 4
      , limits: [5, 10, 15]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        // console.log(AnnouncementData.count);
        num = obj.limit;
        pag = obj.curr;
        AnnouncementData.limit = num;
        AnnouncementData.page = pag;
        const { code, data } = await ajax({ url: "Announcement/getAnnouncement", type: "get", data: { value, num, pag } });
        // console.log(data);
        showTr(data);
      }
    });
  });
}


$("#father").on("click", "dd", function (e) {
  const clssName = $(e.target).attr("id");
  $("#main").children().hide();
  $(`.${clssName}`).show();
  tablePageShow();
  localStorage.name = clssName;
})
//搜索
$("#searchBtn").click(async function (e) {
  const value = $("#demoReload").val();
  const { code, data } = await ajax({ url: "Announcement/getAnnouncement", type: "get", data: { value, } });
  console.log(data.length)
  AnnouncementData.count = data.length;
  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    // console.log(AnnouncementData.count);
    //完整功能
    laypage.render({
      elem: 'demo7'
      , count: AnnouncementData.count
      , limit: 2
      , limits: [3, 4, 5]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        // console.log(AnnouncementData.count);
        let num = obj.limit;
        let pag = obj.curr;
        const { code, data } = await ajax({ url: "Announcement/getAnnouncement", type: "get", data: { value, num, pag } });
        showTr(data);
      }
    });
  });
  showTr(data);
})

window.addEventListener('pageshow', async function (event) {
  if (event.persisted || window.performance && window.performance.navigation.type == 2) {
    let cls = localStorage.name;
    //  console.log(5555);
    $(`#${cls}`).parent().attr("class", "layui-this");
    $(`#${cls}`).parent().parent().parent().attr("class", "layui-nav-item layui-nav-itemed")
    $(`.${cls}`).show();
    var value = "";
    value = value.trim();
    let num = AnnouncementData.limit;
    let pag = 2;
    const { code, data, countNum } = await ajax({ url: "Announcement/getAnnouncement", type: "get", data: { value, num, pag } });
    AnnouncementData.count = countNum.length;
    //分页
    layui.use(['laypage', 'layer'], function () {
      var laypage = layui.laypage
        , layer = layui.layer;
      // console.log(AnnouncementData.count);
      //完整功能
      laypage.render({
        elem: 'demo7'
        , count: AnnouncementData.count
        , limit: 2
        , limits: [3, 4, 5]
        , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
        , jump: async function (obj) {
          // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
          // console.log(obj.limit); //得到每页显示的条数
          // console.log(AnnouncementData.count);
          num = obj.limit;
          pag = obj.curr;
          const { code, data } = await ajax({ url: "Announcement/getAnnouncement", type: "get", data: { value, num, pag } });
          // console.log(data);
          showTr(data);
        }
      });
    });
  }
}, false);

$("tbody").on("click", "#up", function (e) {
  let id = $(e.target).data("val");
  // console.log(id);
  location.href = `update.html?id=${id}`;

})
$("tbody").on("click", "#del", async function (e) {
  let id = $(e.target).data("val");
  const delRes = confirm("确认删除");
  if (delRes) {
    // console.log($('#del'));
    const { code, message } = await ajax({ url: "Announcement/delData", type: "post", data: { id } });
    if (code) {
      alert(message);
      tablePageShow();
    }
  }

})

//excel上传
$("#excelExport").click(function () {
  // console.log(55555);
  var exportFileContent = document.getElementById("table_report").outerHTML
  var blob = new Blob([exportFileContent], { type: "text/plain;charset=utf-8" });         //解决中文乱码问题
  blob = new Blob([String.fromCharCode(0xFEFF), blob], { type: blob.type });
  var link = window.URL.createObjectURL(blob);
  var a = document.createElement("a");    //创建a标签
  a.download = "企业反映问题诉求汇总表.xls";  //设置被下载的超链接目标（文件名）
  a.href = link;                            //设置a标签的链接
  document.body.appendChild(a);            //a标签添加到页面
  a.click();                                //设置a标签触发单击事件
  document.body.removeChild(a);

})

//保修登记
$('.maintenanceAdd').click(async function (e) {
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['800px', '600px'], //宽高
    content: `<form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">小区</label>
                    <div class="layui-input-block">
                      <select name="community" lay-verify="required">
                      </select>
                    </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">房间号</label>
                  <div class="layui-input-block">
                    <input type="text" name="roomNumber" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">申请人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="applicant" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                  <label class="layui-form-label">联系电话</label>
                  <div class="layui-input-inline">
                    <input type="text" name="applicantPhone" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item layui-form-text">
                  <label class="layui-form-label">详细情况</label>
                  <div class="layui-input-block">
                    <textarea name="detailedInformation" placeholder="请输入内容" class="layui-textarea"></textarea>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">紧急程度</label>
                  <div class="layui-input-block">
                    <select name="emergencyType" lay-verify="required">
                    <option value="0">一般</option>
                    <option value="1">紧急</option>
                    <option value="2">严重</option>
                    </select>
                  </div>
                </div>
               
                <div class="layui-inline">
                  <label class="layui-form-label">预约时间</label>
                  <div class="layui-input-inline">
                      <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test1" name="startTime" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-inline">
                <label class="layui-form-label" id="timeover">要求完成时间</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test1" name="endtTime" autocomplete="off" class="layui-input">
                </div>
              </div>
               
              <div class="layui-form-item">
              <div class="layui-inline">
                <label class="layui-form-label">类型</label>
                <div class="layui-input-inline">
                  <select name="type" lay-filter="test3" lay-verify="" id="type" class="layui-form">
                  <option value="0">保修</option>
                  <option value="1">投诉</option>
                  <option value="2">建议</option>
                  </select>
                </div>
                <label class="layui-form-label">来源</label>
                <div class="layui-input-inline">
                  <select name="source" lay-filter="test3" lay-verify="" id="source" class="layui-form">
                          <option value="0">上门</option>
                          <option value="1">电话</option>
                  </select>
                </div>
              </div>
              
              <div class="layui-form-item">
                  <label class="layui-form-label">受理人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="accept" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                  <label class="layui-form-label">受理时间 </label>
                  <div class="layui-input-inline">
                  <input type="text" class="layui-input" id="test1" name="acceptTime" autocomplete="off" class="layui-input">
                  </div>
                </div>

                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" id="save" lay-submit lay-filter="formDemo">保存</button>
                    <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
                  </div>
                </div>
              </form>`

  });
  layui.use('laydate', function () {
    var laydate = layui.laydate;

    //执行一个laydate实例
    laydate.render({
      elem: '#test1' //指定元素
    });
  });
  const { code, data } = await ajax({ url: "Community/getList", type: "post" });
  const xiaoquOption = data.map(item => (
    `
        <option value="${item._id}">${item.name}</option>
    `
  )).join('');
  $('[name=community]').html(xiaoquOption);
  renderForm();
})

$("html").on("click", "#save", async function (e) {
  e.preventDefault();
  const communityId = $('[name=community]').val();
  const roomNumber = $('[name=roomNumber]').val();
  const applicant = $("[name=applicant]").val();
  const applicantPhone = $("[name=applicantPhone]").val();
  const detailedInformation = $("[name=detailedInformation]").val();
  const emergencyType = $("[name=emergencyType]").val();
  const startTime = $("[name=startTime]").val();
  const endtTime = $("[name=endtTime]").val();
  const type = $("[name=type]").val();
  const source = $("[name=source]").val();
  const accept = $("[name=accept]").val();
  const acceptTime = $("[name=acceptTime]").val();
  const sendSingle = 0;
  const dataType = 1;
  // console.log(community,roomNumber,applicant,applicantPhone,detailedInformation,emergencyType,startTime,endtTime,type,source,accept,acceptTime);
  const { code, message } = await ajax({ url: "Repair/add", type: "post", data: { communityId, roomNumber, applicant, applicantPhone, detailedInformation, emergencyType, startTime, endtTime, type, source, accept, acceptTime, sendSingle, dataType } });
  if (code) {
    alert(message);
    firstShow();
  }
})
function getreceipt(res) {
  if (res == 1) {
    return "已派单";
  } else if (res == 0) {
    return "未派单";
  } else if (res == 2) {
    return "已完成";
  }
}
function getTrShow(findNum) {
  // console.log(findNum)
  const trs = findNum.map(item => (
    `
    <tr>
        <td>${item.communityId ? item.communityId.name : ""}</td>
        <td>${item.roomNumber}</td>
        <td>${item.source ? "电话" : "上门"}</td>
        <td>${item.applicant}</td>
        <td>${item.applicantPhone}</td>
        <td>${getType(item.type)}</td>
        <td>${getemergencyType(item.emergencyType)}</td>
        <td>${item.acceptTime}</td>
        <td>${item.endtTime}</td>
        <td>
        ${getreceipt(item.sendSingle)}
        </td>
        <td>
            ${item.sendSingle ? `<button data-val="${item._id}" 	class="layui-btn layui-btn-primary updateRepair" >编辑</button> <button class="layui-btn layui-btn-primary receiptBtn" data-val="${item._id}" >回单</button> <button 	class="layui-btn layui-btn-primary delData" data-val="${item._id}">删除</button>` : `<button 	class="layui-btn layui-btn-primary updateRepair" data-val="${item._id}">编辑</button> <button 	class="layui-btn layui-btn-primary single" data-val="${item._id}">派单</button> <button class="layui-btn layui-btn-primary receiptBtn" data-val="${item._id}">回单</button> <button class="layui-btn layui-btn-primary delData" data-val="${item._id}">删除</button>`}
        </td>
    </tr>
    `
  )).join('');

  $("#maintenance-content").html(trs);
}

async function showPage(num) {
  let page = aboutMaintenance.page;
  let limit = aboutMaintenance.limit;
  const val = $("#repairVal").val() ? $("#repairVal").val() : '';
  const { code, message, data: { findNum, findResult } } = await ajax({ url: "Repair/find", type: "get", data: { limit, page, val } });
  getTrShow(findNum);
  renderForm();

}

async function getList() {
  const limit = 2;
  const page = 1;
  const { code, message, data: { findNum, findResult } } = await ajax({ url: "Repair/find", type: "get", data: { limit, page } });
  RepairData.count = findResult.length;
  showPage(RepairData.count);
}
$("#aboutMaintenance").click(async function (e) {
  // getList();
  const limit = 2;
  const page = 1;
  const { code, message, data: { findNum, findResult } } = await ajax({ url: "Repair/find", type: "get", data: { limit, page } });
  RepairData.count = findResult.length;
  // showPage(RepairData.count);

  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    //完整功能
    laypage.render({
      elem: 'demo6'
      , count: RepairData.count
      , limit: 3
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        const limit = obj.limit;
        const page = obj.curr;
        aboutMaintenance.page = page;
        aboutMaintenance.limit = limit;
        const val = $("#repairVal").val() ? $("#repairVal").val() : '';
        const { code, message, data: { findNum, findResult } } = await ajax({ url: "Repair/find", type: "get", data: { limit, page, val } });
        getTrShow(findNum);
        renderForm();
      }
    });
  });
})

function getType(res) {
  if (res == 1) {
    return "投诉";
  } else if (res == 2) {
    return "建议";
  } else {
    return "报修";
  }
}

function getemergencyType(res) {
  if (res == 1) {
    return "紧急";
  } else if (res == 2) {
    return "严重";
  } else {
    return "一般";
  }
}

async function firstShow() {
  const val = $("#repairVal").val() ? $("#repairVal").val() : '';
  // 
  const { data: { findNum, findResult } } = await ajax({ url: "Repair/find", type: "get", data: { val } });
  // console.log(findNum);
  RepairData.count = findNum.length;
  showPage(RepairData.count)
}

$("#searchRepair").click(async function (e) {
  // firstShow();
  const val = $("#repairVal").val() ? $("#repairVal").val() : '';
  const { data: { findNum, findResult } } = await ajax({ url: "Repair/find", type: "get", data: { val } });
  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    //完整功能
    laypage.render({
      elem: 'demo6'
      , count: findNum.length
      , limit: 3
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        const limit = obj.limit;
        const page = obj.curr;
        const val = $("#repairVal").val() ? $("#repairVal").val() : '';
        const { code, message, data: { findNum, findResult } } = await ajax({ url: "Repair/find", type: "get", data: { limit, page, val } });
        getTrShow(findNum);
        renderForm();
      }
    });
  });
})


$('html').on("click", ".updateRepair", async function (e) {
  const id = $(e.target).data("val");
  // console.log(id);
  const { data: [{ communityId: { _id, name }, _id: listid, roomNumber, applicant, applicantPhone, detailedInformation, emergencyType, startTime, endtTime, type, source, accept, acceptTime }] } = await ajax({ url: "Repair/findOne", type: "post", data: { id } });
  // console.log(_id);
  const { code, data } = await ajax({ url: "Community/getList", type: "post" });

  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['800px', '600px'], //宽高
    content: `<form class="layui-form" action="" id="formShow">
                <div class="layui-form-item">
                    <label class="layui-form-label">小区</label>
                    <div class="layui-input-block">
                      <select name="community" lay-verify="required">
                      </select>
                    </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">房间号</label>
                  <div class="layui-input-block">
                    <input type="text" name="roomNumber" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">申请人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="applicant" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                  <label class="layui-form-label">联系电话</label>
                  <div class="layui-input-inline">
                    <input type="text" name="applicantPhone" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item layui-form-text">
                  <label class="layui-form-label">详细情况</label>
                  <div class="layui-input-block">
                    <textarea name="detailedInformation" placeholder="请输入内容" class="layui-textarea"></textarea>
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">紧急程度</label>
                  <div class="layui-input-block">
                    <select name="emergencyType" lay-verify="required">
                    <option value="0">一般</option>
                    <option value="1">紧急</option>
                    <option value="2">严重</option>
                    </select>
                  </div>
                </div>
               
                <div class="layui-inline">
                  <label class="layui-form-label">预约时间</label>
                  <div class="layui-input-inline">
                      <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test1" name="startTime" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-inline">
                <label class="layui-form-label" id="timeover">要求完成时间</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test1" name="endtTime" autocomplete="off" class="layui-input">
                </div>
              </div>
               
              <div class="layui-form-item">
              <div class="layui-inline">
                <label class="layui-form-label">类型</label>
                <div class="layui-input-inline">
                  <select name="type" lay-filter="test3" lay-verify="" id="type" class="layui-form">
                  <option value="0">保修</option>
                  <option value="1">投诉</option>
                  <option value="2">建议</option>
                  </select>
                </div>
                <label class="layui-form-label">来源</label>
                <div class="layui-input-inline">
                  <select name="source" lay-filter="test3" lay-verify="" id="source" class="layui-form">
                          <option value="0">上门</option>
                          <option value="1">电话</option>
                  </select>
                </div>
              </div>
              
              <div class="layui-form-item">
                  <label class="layui-form-label">受理人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="accept" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                  <label class="layui-form-label">受理时间 </label>
                  <div class="layui-input-inline">
                  <input type="text" class="layui-input" id="test1" name="acceptTime" autocomplete="off" class="layui-input">
                  </div>
                </div>

                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" id="updateRepair" lay-submit lay-filter="formDemo">保存</button>
                    <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
                  </div>
                </div>
              </form>`

  });

  layui.use('laydate', function () {
    var laydate = layui.laydate;
    //执行一个laydate实例
    laydate.render({
      elem: '#test1' //指定元素
    });
  });
  const xiaoquOption = data.map(item => {
    if (_id == item._id) {
      return ` <option value="${item._id}" selected="selected">${item.name}</option>`
    } else {
      return ` <option value="${item._id}" >${item.name}</option>`
    }
  }).join('');
  $('[name=community]').html(xiaoquOption);
  $('[name=roomNumber]').val(roomNumber);
  $('[name=applicant]').val(applicant);
  $('[name=applicantPhone]').val(applicantPhone);
  $('[name=detailedInformation]').val(detailedInformation);
  $(`[name=emergencyType]`).val(emergencyType).attr("selected", true);
  $(`[name=type]`).val(type).attr("selected", true);
  $(`[name=source]`).val(source).attr("selected", true);
  $('[name=startTime]').val(startTime);
  $('[name=endtTime]').val(endtTime);
  $('[name=accept]').val(accept);
  $('[name=acceptTime]').val(acceptTime);
  $("#updateRepair").attr("data-val", listid)
  renderForm();
  // console.log(listid);
})

// $("html").on("click", "#goback", function (e) {
//   e.preventDefault();
//   $('element.style').hide();
//   $("element.style").css("background-color","");
// })

$("html").on("click", "#updateRepair", async function (e) {
  e.preventDefault();
  const communityId = $('[name=community]').val();
  const roomNumber = $('[name=roomNumber]').val();
  const applicant = $('[name=applicant]').val();
  const applicantPhone = $('[name=applicantPhone]').val();
  const detailedInformation = $('[name=detailedInformation]').val();
  const emergencyType = $(`[name=emergencyType]`).val();
  const type = $(`[name=type]`).val();
  const source = $(`[name=source]`).val();
  const startTime = $('[name=startTime]').val();
  const endtTime = $('[name=endtTime]').val();
  const accept = $('[name=accept]').val();
  const acceptTime = $('[name=acceptTime]').val();
  const id = $(e.target).data("val");
  const { code, message } = await ajax({ url: "Repair/updateOne", type: "post", data: { id, communityId, roomNumber, applicant, applicantPhone, detailedInformation, emergencyType, type, source, startTime, endtTime, accept, acceptTime } });
  if (code) {
    alert(message);
    firstShow();
  }
})


$("html").on("click", ".single", async function (e) {
  const id = $(e.target).data("val");
  const { code, data: [{ communityId: { _id, name }, roomNumber, applicant, applicantPhone, emergencyType, endtTime, detailedInformation }] } = await ajax({ url: "Repair/findOne", type: "post", data: { id } });

  // console.log(findOne);

  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['800px', '600px'], //宽高
    content: `<form class="layui-form" action="" id="formShow">
                <div className="layui-form-item">
                  <h1>报事报修派工</h1>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">地址</label>
                  <div class="layui-input-block">
                    <input type="text" name="addressAssigned" required  lay-verify="required"  autocomplete="off" class="layui-input" readonly="readonly">
                  </div>
                </div>
               
                <div class="layui-form-item">
                  <label class="layui-form-label">申请人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="applicantAssigned" required lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>
                  <label class="layui-form-label">联系电话</label>
                  <div class="layui-input-inline">
                    <input type="text" name="applicantPhoneAssigned" required lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>
                </div>
                
                <div class="layui-form-item">
                  <label class="layui-form-label">紧急程度</label>
                  
                  <div class="layui-input-inline">
                    <input type="text" name="emergencyTypeAssigned" required lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>

                  <label class="layui-form-label">要求完成时间</label>
                  <div class="layui-input-inline">
                    <input type="text" name="endtimerequirements" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                </div>
          
                <div class="layui-form-item">
                <label class="layui-form-label">详细情况</label>
                <div class="layui-input-block">
                  <input type="text" name="detailedAssigned" required  lay-verify="required"  autocomplete="off" class="layui-input" readonly="readonly">
                </div>
              </div>
              <div className="layui-form-item">
                  <h1>派工信息</h1>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                      <label class="layui-form-label">指派给</label>
                      <div class="layui-input-inline">
                        <select name="AssignedPeople">
                        </select>
                      </div>

                      <label class="layui-form-label" id="timeover">要求完成时间</label>
                      <div class="layui-input-inline">
                          <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test1" name="AssignedendtTime" autocomplete="off" class="layui-input">
                      </div>
                </div>

                <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">服务类型</label>
                  <div class="layui-input-inline">
                    <select name="AssignedType">
                        <option value="0">免费</option>
                        <option value="1">收费</option>
                    </select>
                  </div>
                </div>
                <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">详细情况</label>
                <div class="layui-input-block">
                  <textarea name="detailedInformationAssigned" placeholder="请输入内容" class="layui-textarea"></textarea>
                </div>
              </div>
                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" id="requirementsBtn" lay-submit lay-filter="formDemo">保存</button>
                    <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
                  </div>
                </div>
              </form>`

  });
  $('[name=addressAssigned]').val(name + roomNumber);
  $('[name=applicantAssigned]').val(applicant);
  $('[name=applicantPhoneAssigned]').val(applicantPhone);
  $('[name=emergencyTypeAssigned]').val(getemergencyType(emergencyType));
  $('[name=endtimerequirements]').val(endtTime);
  $('[name=detailedAssigned]').val(detailedInformation);
  $("#requirementsBtn").attr("data-val", id);

  const { data } = await ajax({ url: "MaintenanceUser/getAll", type: "post" });
  const options = data.map(item => (
    `
      <option value="${item._id}">${item.name}</option>
    `
  )).join("");
  $("[name=AssignedPeople]").html(options);
  layui.use('laydate', function () {
    var laydate = layui.laydate;

    //执行一个laydate实例
    laydate.render({
      elem: '#test1' //指定元素
    });
  });
  renderForm();
})


function getCurrentDate() {
  const date = new Date();
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  var d = date.getDate();
  var h = date.getHours();
  var min = date.getMinutes();
  var s = date.getSeconds();
  var str = y + '年' + (m < 10 ? ('0' + m) : m) + '月' + (d < 10 ? ('0' + d) : d) + '日  ' + (h < 10 ? ('0' + h) : h) + ':' + (min < 10 ? ('0' + min) : min) + ':' + (s < 10 ? ('0' + s) : s);
  return str;
}

$("html").on("click", "#requirementsBtn", async function (e) {
  e.preventDefault();
  const AnnouncementId = $(e.target).data("val");

  const userId = $("[name=AssignedPeople]").val();
  const endtime = $("[name=AssignedendtTime]").val();
  const type = $("[name=AssignedType]").val();
  const contentData = $("[name=detailedInformationAssigned]").val();
  const starttime = getCurrentDate();
  const { code, message } = await ajax({ url: "Maintenance/add", type: "post", data: { AnnouncementId, userId, endtime, type, contentData, starttime } });
  if (code) {
    alert(message);
    firstShow();
  }
})


$("html").on("click", ".receiptBtn", async function (e) {
  // console.log(88888);
  const id = $(e.target).data("val");
  const { code, data: [{ communityId: { _id, name }, roomNumber, applicant, applicantPhone, emergencyType, endtTime, detailedInformation }] } = await ajax({ url: "Repair/findOne", type: "post", data: { id } });

  // console.log(findOne);

  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['800px', '600px'], //宽高
    content: `<form class="layui-form" action="" id="formShow">
                <div className="layui-form-item">
                  <h1>回单</h1>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">地址</label>
                  <div class="layui-input-block">
                    <input type="text" name="addressReceipt" required  lay-verify="required"  autocomplete="off" class="layui-input" readonly="readonly">
                  </div>
                </div>
               
                <div class="layui-form-item">
                  <label class="layui-form-label">申请人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="applicantReceipt" required lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>
                  <label class="layui-form-label">联系电话</label>
                  <div class="layui-input-inline">
                    <input type="text" name="applicantPhoneReceipt" required lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>
                </div>
                
                <div class="layui-form-item">
                  <label class="layui-form-label">紧急程度</label>
                  
                  <div class="layui-input-inline">
                    <input type="text" name="emergencyTypeReceipt" required lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>

                  <label class="layui-form-label">要求完成时间</label>
                  <div class="layui-input-inline">
                    <input type="text" name="endtimeReceipt" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                  </div>
                </div>
          
                <div class="layui-form-item">
                <label class="layui-form-label">详细情况</label>
                <div class="layui-input-block">
                  <input type="text" name="detailedReceipt" required  lay-verify="required"  autocomplete="off" class="layui-input" readonly="readonly">
                </div>
              </div>
              <div className="layui-form-item">
                  <h1>回单信息</h1>
                </div>
      
                <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">处理情况</label>
                  <div class="layui-input-inline">
                    <select name="ReceiptType">
                        <option value="0">已完成</option>
                        <option value="1">未完成</option>
                    </select>
                  </div>
                </div>
                <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                  <textarea name="detailedInformationReceipt" placeholder="请输入内容" class="layui-textarea"></textarea>
                </div>
              </div>
                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" id="ReceiptBtn" lay-submit lay-filter="formDemo">保存</button>
                    <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
                  </div>
                </div>
              </form>`

  });
  $('[name=addressReceipt]').val(name + roomNumber);
  $('[name=applicantReceipt]').val(applicant);
  $('[name=applicantPhoneReceipt]').val(applicantPhone);
  $('[name=emergencyTypeReceipt]').val(getemergencyType(emergencyType));
  $('[name=endtimeReceipt]').val(endtTime);
  $('[name=detailedReceipt]').val(detailedInformation);
  $("#ReceiptBtn").attr("data-val", id);
  layui.use('laydate', function () {
    var laydate = layui.laydate;

    //执行一个laydate实例
    laydate.render({
      elem: '#test1' //指定元素
    });
  });
  renderForm();
})


$("html").on("click", "#ReceiptBtn", async function (e) {
  e.preventDefault();
  const id = $(e.target).data("val");
  const ReceiptType = $("[name=ReceiptType]").val();
  const detailedInformationReceipt = $("[name=detailedInformationReceipt]").val();
  const { code, message } = await ajax({ url: "Maintenance/addReceipt", type: "post", data: { id, ReceiptType, detailedInformationReceipt } });
  if (code) {
    alert(message);
  }
})


$("html").on("click", ".delData", async function (e) {
  e.preventDefault();
  const id = $(e.target).data("val");
  console.log(id);
  const { code, message } = await ajax({ url: "Repair/del", type: "post", data: { id } });
  if (code) {
    alert(message);
    firstShow();
  }
})


$("#management").click(async function (e) {
  const { code, message, data } = await ajax({ url: "Maintenance/getAll", type: "post" });

  const trs = data.map(item => (
    `
      <tr>
          <td>${item.starttime}</td>
          <td>${item.AnnouncementId.accept}</td>
          <td>${item.AnnouncementId.communityId.name}${item.AnnouncementId.roomNumber}</td>
          <td>${item.AnnouncementId.detailedInformation}</td>
          <td>${item.contentData}</td>
          <td>${item.endtime}</td>
          <td>${item.ReceiptType ? "已完成" : "未完成"}</td>
      </tr>
    `
  )).join("");
  console.log(data);
  $("#Dispatching-content").html(trs)
})

function showOption(data, name, CommunityId) {
  var option = data.map(item => (
    `
      <option value="${item._id}">${item.name}</option>
    `
  )).join("");
  $(name).html(option);
}


$(".entry").click(async function (e) {
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['800px', '600px'], //宽高
    content: `<form class="layui-form" action="" id="formShow">
                <div className="layui-form-item">
                  <h1>录入投诉</h1>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">请选择小区</label>
                  <div class="layui-input-block " id="small">
                      <select name="CommunityId" ></select>
                  </div>
                  
                </div>

                <div class="layui-form-item">
                  <label class="layui-form-label">楼栋</label>
                  <div class="layui-input-inline">
                      <select name="buildingsId">
                          <option >请选择楼栋</option>
                      </select>
                  </div>
                  <div class="layui-input-inline">
                      <select name="unitId">
                          <option >请选择单元</option>
                      </select>
                  </div>
                  <div class="layui-input-inline">
                      <select name="RoomNumId">
                          <option >请选择门牌号</option>
                      </select>
                  </div>
                </div>
                
                <div class="layui-form-item">
                  <label class="layui-form-label">投诉人</label>
                  <div class="layui-input-block">
                    <input type="text" name="ComplaintsPeople" required  lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input small">
                  </div>
                </div>

                <div class="layui-form-item">
                <label class="layui-form-label">联系人电话</label>
                <div class="layui-input-block">
                  <input type="text" name="Phone" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input small">
                </div>
              </div>

              <div class="layui-form-item">
              <div class="layui-inline">
                <label class="layui-form-label">投诉时间</label>
                <div class="layui-input-inline">
                  <input type="text" name="complaintsDate" class="layui-input" id="test4" placeholder="yyyy-MM-dd">
                </div>
              </div>
            </div>

                <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                  <textarea name="ComplaintsContent" placeholder="请输入内容" class="layui-textarea small"></textarea>
                </div>
              </div>
                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" id="ComplaintsBtn" lay-submit lay-filter="formDemo">保存</button>
                    <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
                  </div>
                </div>
              </form>`

  });

  const { code, data } = await ajax({ url: "Community/getList", type: "post" });
  const res = await ajax({ url: "Buildings/getAll", type: "post" });
  const resUnit = await ajax({ url: "Unit/getAll", type: "post" });
  const RoomNum = await ajax({ url: "RoomNum/getAll", type: "post" });
  // console.log(RoomNum)
  showOption(data, "[name=CommunityId]");
  showOption(res.data, "[name=buildingsId]");
  showOption(resUnit.dataAll, "[name=unitId]");
  showOption(RoomNum.dataAll, "[name=RoomNumId]");
  layui.use('laydate', function () {
    var laydate = layui.laydate;

    //执行一个laydate实例
    laydate.render({
      elem: '#test4' //指定元素
    });
  });
  renderForm();
})


$("html").on("click", "#ComplaintsBtn", async function (e) {
  e.preventDefault();
  const CommunityId = $("[name=CommunityId]").val();
  const buildingsId = $("[name=buildingsId]").val();
  const unitId = $("[name=unitId]").val();
  const RoomNumId = $("[name=RoomNumId]").val();
  const ComplaintsPeople = $("[name=ComplaintsPeople]").val();
  const Phone = $("[name=Phone]").val();
  const complaintsDate = $("[name=complaintsDate]").val();
  const ComplaintsContent = $("[name=ComplaintsContent]").val();
  const ComplaintsType = 0;
  const { code, message } = await ajax({ url: "Complaints/add", type: "post", data: { CommunityId, buildingsId, unitId, RoomNumId, ComplaintsPeople, Phone, complaintsDate, ComplaintsContent, ComplaintsType } });
  if (code) {
    alert(message);
  }
  // console.log(CommunityId,buildingsId,unitId,RoomNumId,ComplaintsPeople,Phone,complaintsDate,ComplaintsContent);
})

function complaints(dataNum) {
  // console.log(dataNum);
  const trs = dataNum.map(item => (
    `
      <tr>
          <td>${item.CommunityId ? item.CommunityId.name : "信息不存在"}</td>
          <td>${item.buildingsId ? item.buildingsId.name : ""}${item.unitId ? item.unitId.name : ""}${item.RoomNumId ? item.RoomNumId.name : "信息不存在"}</td>
          <td>${item.ComplaintsPeople}</td>
          <td>${item.complaintsDate}</td>
          <td>${item.Phone}</td>
          <td>${item.ComplaintsType ? "已受理" : "未受理"}</td>
          <td>${item.ComplaintsContent}</td>
          <td>${item.AcceptPeople ? item.AcceptPeople : ""}</td>
          <td>${item.AcceptDate ? item.AcceptDate : ""}</td>
          <td>
              <button type="button" class="layui-btn layui-btn-primary" data-val="${item._id}" id="accept">受理</button>
              <button type="button" class="layui-btn layui-btn-primary" data-val="${item._id}" id="vist">回访</button>
          </td>
      </tr>
    `
  )).join("");
  $("#complaints-content").html(trs);
}
const pageData = {
  limit: 0,
  page: 0
};
$("#complaints").click(async function (e) {
  var limit = 4;
  var page = 1;
  var value = "";
  const { dataNum, count } = await ajax({ url: "Complaints/findNum", type: "post", data: { limit, page, value } });
  complaints(dataNum);
  // console.log(CountNum);
  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    //完整功能
    laypage.render({
      elem: 'demo3'
      , count: count.length
      , limit: 4
      , limits: [5, 10, 15]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        page = obj.curr;
        limit = obj.limit;
        value = $("[name=complaintsVal]").val();
        const res = await ajax({ url: "Complaints/findNum", type: "post", data: { limit, page, value } });
        pageData.limit = limit;
        pageData.page = page;
        complaints(res.dataNum);
      }
    });
  });
})

$("#complaintssearchBtn").click(async function (e) {
  var value = $("[name=complaintsVal]").val();
  var limit = 4;
  var page = 1;
  const { dataNum, count } = await ajax({ url: "Complaints/findNum", type: "post", data: { limit, page, value } });
  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    //完整功能
    laypage.render({
      elem: 'demo3'
      , count: count.length
      , limit: 4
      , limits: [5, 10, 15]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        page = obj.curr;
        limit = obj.limit;
        value = $("[name=complaintsVal]").val();
        const res = await ajax({ url: "Complaints/findNum", type: "post", data: { limit, page, value } });
        complaints(res.dataNum);
      }
    });
  });
})

$("html").on("click", "#accept", function (e) {
  var id = $(e.target).data("val");

  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['400px', '400px'], //宽高
    content: `<form class="layui-form" action="" id="formShow">
                <div className="layui-form-item">
                  <h1>受理</h1>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">处理人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="deal" required  lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>
                </div>
               
                <div class="layui-form-item">
                  <div class="layui-inline">
                    <label class="layui-form-label">是否解决</label>
                    <div class="layui-input-inline">
                      <select name="dealType">
                          <option value="0">未解决</option>
                          <option value="1">已解决</option>
                      </select>
                    </div>
                  </div>

                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" id="deal" data-val="${id}" lay-submit lay-filter="formDemo">保存</button>
                    <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
                  </div>
                </div>
              </form>`

  });

  renderForm();
})

$("html").on("click", "#deal", async function (e) {
  e.preventDefault();
  const id = $(e.target).data("val");
  console.log(id);
  const AcceptPeople = $('[name=deal]').val();
  // const ComplaintsType = $("[name=dealType]").val();
  const ComplaintsType = 1;
  const AcceptDate = getCurrentDate();
  const { code, message } = await ajax({ url: "Complaints/updateOne", type: "post", data: { id, AcceptPeople, ComplaintsType, AcceptDate } });
  if (code) {
    alert(message);
    var limit = pageData.limit;
    var page = pageData.page;
    var value = "";
    const res = await ajax({ url: "Complaints/findNum", type: "post", data: { limit, page, value } });
    complaints(res.dataNum);
  }
})


$("html").on("click", "#ReturnVist", function (e) {
  const id = $(e.target).data("val");
  // console.log(id);
  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    //完整功能
    laypage.render({
      elem: 'demo3'
      , count: count.length
      , limit: 4
      , limits: [5, 10, 15]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        page = obj.curr;
        limit = obj.limit;
        value = $("[name=complaintsVal]").val();
        const res = await ajax({ url: "Complaints/findNum", type: "post", data: { limit, page, value } });
        complaints(res.dataNum);
      }
    });
  });
})

$("html").on("click", "#vist", function (e) {
  var id = $(e.target).data("val");
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['600px', '600px'], //宽高
    content: `<form class="layui-form" action="" >
                <div className="layui-form-item">
                  <h1>回访</h1>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">回访人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="ReturnVistDeal" required  lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>
                </div>
               
                <div class="layui-form-item">
                  <div class="layui-inline">
                    <label class="layui-form-label">是否解决</label>
                    <div class="layui-input-inline">
                      <select name="solve">
                          <option value="0">未解决</option>
                          <option value="1">已解决</option>
                      </select>
                    </div>
                  </div>
                  <div class="layui-form-item">
                  <div class="layui-inline">
                    <label class="layui-form-label">是否满意</label>
                    <div class="layui-input-inline">
                      <select name="Satisfied">
                          <option value="0">满意</option>
                          <option value="1">不满意</option>
                      </select>
                    </div>
                  </div>

                  <div class="layui-form-item layui-form-text">
                  <label class="layui-form-label">备注</label>
                  <div class="layui-input-block">
                    <textarea name="note" placeholder="请输入内容" class="layui-textarea text-small"></textarea>
                  </div>
                </div>


                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" id="vistBtn" data-val="${id}" lay-submit lay-filter="formDemo">保存</button>
                    <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
                  </div>
                </div>
              </form>`

  });

  renderForm();
})

$("html").on("click", "#vistBtn", async function (e) {
  e.preventDefault();
  const ComplaintsId = $(e.target).data("val");
  console.log(ComplaintsId);
  const name = $("[name=ReturnVistDeal]").val();
  const solve = $("[name=solve]").val();
  const Satisfied = $("[name=Satisfied]").val();
  const note = $("[name=note]").val();
  const { code, message } = await ajax({ url: "ReturnVist/add", type: "post", data: { name, solve, Satisfied, ComplaintsId, note } });
  if (code) {
    alert(message);
  }
})

function getDecor(res) {

  return res.map(item => (`
      <option value="${item._id}">${item.name}</option>
  `)).join('');
  // renderForm();
  // console.log(opt);
  $("#decoFrom").html(opt);
  // return opt;
}

function getDecorateContent(getAll) {
  return getAll.map(item => (
    `
      <tr>
          <td>${item.CommunityId ? item.CommunityId.name : ""}</td>
          <td>${item.buildingsId ? item.buildingsId.name : ""}${item.unitId ? item.unitId.name : ""}${item.RoomNumId ? item.RoomNumId.name : ""}</td>
          <td>${item.ConstructionUnit}</td>
          <td>${item.applicant}</td>
          <td>${item.applyTime}</td>
          <td>${item.type ? "已审批" : "未审批"}</td>
          <td>
            <form  class="layui-form" id="decoFrom">
              <div class="layui-inline">
                  <div class="layui-input-inline">
                    <select name="quiz">
                    ${item.DecorateId ? getDecor(item.DecorateId) : ""}
                    </select>
                  </div>
                </div>
            </form>
          </td>
          <td>${item.approver ? item.approver : ""}</td>
          <td>
          ${item.type ? `` : `<button type="button" class="layui-btn layui-btn-primary" data-val="${item._id}" id="decoacceptance">验收</button>`}
          <button type="button" class="layui-btn layui-btn-primary" data-val="${item._id}" id="decoupdate">编辑</button>
          <button type="button" class="layui-btn layui-btn-primary" data-val="${item._id}" id="decodel">删除</button>
          </td>
      </tr>
    `
  )).join('');
}
//装修管理
const decorateObj = {
  limit: 0,
  page: 0,
}
async function getContentShow(limit, page) {
  decorateObj.limit = limit;
  decorateObj.page = page;
  let value = $("[name=decorateVal]").val() ? $("[name=decorateVal]").val() : "";
  const { getCount, getAll } = await ajax({ url: "Decorate/getAll", type: "get", data: { limit, page, value } });
  // console.log(getCount)
  const trs = getDecorateContent(getAll)
  $("#decorate-content").html(trs);
  renderForm();
}
$("#decorate").click(async function () {
  let value = "";
  const { getAll } = await ajax({ url: "Decorate/getAll", type: "get", data: { value } });
  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    //完整功能
    laypage.render({
      elem: 'demo4'
      , count: getAll.length
      , limit: 2
      , limits: [5, 10, 15]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        // console.log(obj)
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        let limit = obj.limit;
        let page = obj.curr;
        getContentShow(limit, page);

      }
    });

  });
})


$(".decorateapply").click(async function (e) {

  const res = await ajax({ url: "Buildings/getAll", type: "post" });
  const resUnit = await ajax({ url: "Unit/getAll", type: "post" });
  const RoomNum = await ajax({ url: "RoomNum/getAll", type: "post" });
  const resCommunity = await ajax({ url: "Community/getList", type: "post" });

  // console.log(resCommunity)
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['650px', '600px'], //宽高
    content: `<form class="layui-form" action="" >
                <div className="layui-form-item">
                  <h1>装修申请</h1>
                </div>
                <div class="layui-form-item">
                <label class="layui-form-label">小区</label>
                <div class="layui-input-block">
                  <select name="communityProjects" lay-filter="aihao">
                  </select>
                </div>
              </div>
               

                <div class="layui-form-item">
                <label class="layui-form-label">楼栋</label>
                <div class="layui-input-block">
                  <select name="buildingChargingProjects" lay-filter="aihao">
                  </select>
                </div>
              </div>
              <div class="layui-form-item">
              <label class="layui-form-label">单元</label>
              <div class="layui-input-block">
                <select name="unitIdChargingProjects" lay-filter="aihao">
                </select>
              </div>
            </div>

            <div class="layui-form-item">
            <label class="layui-form-label">门牌号</label>
            <div class="layui-input-block">
              <select name="RoomNumIdChargingProjects" lay-filter="aihao">
              </select>
            </div>
          </div>

              <div class="layui-form-item">
              <label class="layui-form-label">申请人</label>
              <div class="layui-input-inline">
                <input type="text" name="applicant" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
              <label class="layui-form-label">申请人电话</label>
              <div class="layui-input-inline">
                <input type="text" name="applicantPhone" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
            </div>
            
            <div class="layui-form-item">
              <label class="layui-form-label">施工单位</label>
              <div class="layui-input-block">
                <input type="text" name="ConstructionUnit" autocomplete="off" placeholder="请输入" class="layui-input">
              </div>
            </div>

            <div class="layui-form-item">
            <label class="layui-form-label">负责人</label>
            <div class="layui-input-inline">
              <input type="text" name="head" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label">联系电话</label>
            <div class="layui-input-inline">
              <input type="text" name="headPhone" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>


          <div class="layui-inline">
          <label class="layui-form-label">施工开始时间</label>
          <div class="layui-input-inline">
              <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test4" name="hearStarttime" autocomplete="off" class="layui-input">
          </div>
        </div>
        <div class="layui-inline">
        <label class="layui-form-label" id="timeover">竣工结束时间</label>
        <div class="layui-input-inline">
            <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test4" name="headEndtime" autocomplete="off" class="layui-input">
        </div>
      </div>
          
          <div class="layui-form-item layui-form-text">
              <label class="layui-form-label">收费标准</label>
                <div class="layui-input-block">
                <button type="button" name="DecorateId" class="layui-btn layui-btn-normal" id="addCharge">添加</button>
                  </div>
            </div>
           
            <table class="layui-table">
                  <colgroup>
                    <col width="100">
                    <col width="100">
                    <col>
                  </colgroup>
                  <thead>
                    <tr>
                      <th>收费项目</th>
                      <th>收费标准名称</th>
                      <th>项目类别</th>
                      <th>金额计算方式</th>
                      <th>单价</th>
                      <th>计量方式</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody id="standard-content">

                  </tbody>
          </table>
            

          <div class="layui-form-item layui-form-text">
              <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="noteContent" placeholder="请输入内容" class="layui-textarea text-small"></textarea>
                  </div>
            </div>
              
                 

            <div class="layui-form-item">
            <div class="layui-input-block">
              <button class="layui-btn" id="DecorateBtn"  lay-submit lay-filter="formDemo">保存</button>
              <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
            </div>
          </div>
              
          </form>`

  });

  showOption(res.data, "[name=buildingChargingProjects]");
  showOption(resUnit.dataAll, "[name=unitIdChargingProjects]");
  showOption(RoomNum.dataAll, "[name=RoomNumIdChargingProjects]");
  showOption(resCommunity.data, "[name=communityProjects]");
  layui.use('laydate', function () {
    var laydate = layui.laydate;
    //执行一个laydate实例
    laydate.render({
      elem: '#test4' //指定元素
    });
  });
  renderForm();
})


$("html").on("click", "#addCharge", function (e) {
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['1000px', '600px'], //宽高
    content: `
              <table class="layui-hide" id="test" >
                  <colgroup>
                  <col width="150">
                  <col width="200">
                  <col>
                </colgroup>
                <thead>
                  <tr>
                    <th>收费项目</th>
                    <th>收费标准名称</th>
                    <th>项目类别</th>
                    <th>金额计算方式</th>
                    <th>单价</th>
                    <th>计量方式</th>
                    <th>状态</th>
                  </tr>
                </thead>
                <tbody id="ChargingProjects-content">
                </tbody>
            </table> 
           <div class="inner">
                  <button class="layui-btn  layui-layer-close layui-layer-close1" id="determine" lay-submit lay-filter="formDemo">确定</button>
                  <button  class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</button>
           </div>
    `
  });

  layui.use('table', function () {
    var table = layui.table;
    table.render({
      elem: '#test'
      , url: "http://localhost:8000/ChargingProjects/getAll"
      , id: 'queryList'
      , cols: [[
        { type: 'checkbox' }
        , { field: 'name', width: 150, title: '收费项目', sort: true }
        , { field: 'standard', width: 150, title: '收费标准名称' }
        , { field: 'type', width: 150, title: '项目类别', sort: true }
        , { field: 'calculation', width: 150, title: '金额计算方式' }
        , { field: 'price', title: '单价', minWidth: 100 }
        , { field: 'measurement', width: 150, title: '计量方式', sort: true }
      ]]
      , parseData: function (res) { //res 即为原始返回的数据
        // $("html #ChargingProjects").html(trs);
        return {
          "code": res.code, //解析接口状态
          "msg": res.message, //解析提示文本
          "data": res.data //解析数据列表
        };
      }
      , done: function (res, page, count) {
        //可以自行添加判断的条件是否选中
        //这句才是真正选中，通过设置关键字LAY_CHECKED为true选中，这里只对第一行选中
        if (arr[0] == "all") {
          $('th[data-field=' + 0 + '] input[type="checkbox"]').prop('checked', true);
          $('th[data-field=' + 0 + '] input[type="checkbox"]').next().addClass('layui-form-checked');
          $('tr[data-index] input[type="checkbox"]').prop('checked', true);
          $('tr[data-index] input[type="checkbox"]').next().addClass('layui-form-checked');
        } else {

          for (var i = 0; i < arr.length; i++) {

            $('tr[data-index=' + arr[i] + '] input[type="checkbox"]').prop('checked', true);
            $('tr[data-index=' + arr[i] + '] input[type="checkbox"]').next().addClass('layui-form-checked');
          }
        }
      }
    });



    // renderForm();
    table.on('checkbox', function (obj) {
      // console.log(obj.checked); //当前是否选中状态
      // // console.log(obj.data); //选中行的相关数据
      // console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
      if (obj.type == "all" && obj.checked) {
        arr.length = 0;
        arr.push("all");
      } else if (obj.type == "one" && obj.checked) {
        if (arr[0] == "all") {
          arr.length = 0;
          arr.push(obj.tr.attr("data-index"))
        } else {
          arr.push(obj.tr.attr("data-index"))
        }
      } else if (obj.type == "one" && !obj.checked) {
        arr.splice(arr.indexOf(obj.tr.attr("data-index")), 1);
      } else if (obj.type == "all" && !obj.checked) {
        arr.length = 0;
      }
    });
  });
})
function getQueryList(selectData, res) {
  const trs = selectData.map(item => (
    `
      <tr data-val="${item._id}">
          <td>${item.name}</td>
          <td>${item.standard}</td>
          <td>${item.type}</td>
          <td>${item.calculation}</td>
          <td>${item.price}</td>
          <td>${item.measurement}</td>
          <td>
              <button data-val="${item._id}" class="layui-btn layui-btn-primary" id="decode">删除</button>
          </td>
      </tr>
    `
  )).join('');
  $(res).html(trs);
}
$('html').on("click", "#determine", function (e) {

  selectData = layui.table.checkStatus('queryList').data;
  let res = "#standard-content";
  getQueryList(selectData, res);
})

$("html").on("click", "#decode", function (e) {
  e.preventDefault();
  const id = $(e.target).data("val");
  selectData = selectData.filter(item => item._id != id);
  $(e.target).parents("tr").hide()
  console.log()
  getQueryList(selectData);
})
async function indexShow() {
  var value = $("[name=decorateVal]").val();
  var limit = 4;
  var page = 1;
  const { getCount, getAll } = await ajax({ url: "Decorate/getAll", type: "get", data: { limit, page, value } });

  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    //完整功能
    laypage.render({
      elem: 'demo4'
      , count: getCount.length
      , limit: 2
      , limits: [5, 10, 15]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        page = obj.curr;
        limit = obj.limit;
        value = $("[name=decorateVal]").val();
        // console.log(value);
        const res = await ajax({ url: "Decorate/getAll", type: "get", data: { limit, page, value } });
        getContentShow(limit, page);
      }
    });
  });
}
$("html").on("click", "#DecorateBtn", async function (e) {
  e.preventDefault();
  var DecorateId = [];
  const CommunityId = $("[name=communityProjects]").val();
  const buildingsId = $("[name=buildingChargingProjects]").val();
  const unitId = $("[name=unitIdChargingProjects]").val();
  const RoomNumId = $("[name=RoomNumIdChargingProjects]").val();
  const applicant = $("[name=applicant]").val();
  const applicantPhone = $("[name=applicantPhone]").val();
  const ConstructionUnit = $("[name=ConstructionUnit]").val();
  const head = $("[name=head]").val();
  const headPhone = $("[name=headPhone]").val();
  const hearStarttime = $("[name=hearStarttime]").val();
  const headEndtime = $("[name=headEndtime]").val();
  const noteContent = $("[name=noteContent]").val();
  const applyTime = getCurrentDate();
  const type = 0;
  // DecorateId =  $("#standard-content tr").data("val");
  for (var i = 0; i < $("#standard-content tr").length; i++) {
    DecorateId.push($("#standard-content tr").eq(i).data("val"));
  }
  console.log(DecorateId);
  $.ajax({
    url: "http://192.168.13.6:8000/Decorate/add",
    type: "post",
    data: {
      CommunityId, buildingsId, unitId, RoomNumId, applicant, applicantPhone, ConstructionUnit, head, headPhone, hearStarttime, headEndtime, noteContent, DecorateId, applyTime, type
    },
    traditional: true,
    success(res) {
      if (res.code) {
        alert(res.message);
        indexShow();
      }
    }
  })
})


$("html").on("click", "#decoacceptance", function (e) {
  const id = $(e.target).data("val");
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['400px', '400px'], //宽高
    content: `<form class="layui-form" action="" id="formShow">
                <div className="layui-form-item">
                  <h1>装修审核</h1>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">验收人</label>
                  <div class="layui-input-inline">
                    <input type="text" name="auditPeople" required  lay-verify="required"  autocomplete="off" class="layui-input">
                  </div>
                </div>
               
                <div class="layui-form-item">
                  <div class="layui-inline">
                    <label class="layui-form-label">验收结果</label>
                    <div class="layui-input-inline">
                      <select name="auditType">
                          <option value="0">通过</option>
                          <option value="1">未通过</option>
                      </select>
                    </div>
                  </div>
                  
                  <div class="layui-form-item layui-form-text">
                  <label class="layui-form-label">备注</label>
                  <div class="layui-input-block">
                    <textarea name="auditContent" placeholder="备注" class="layui-textarea" id="texa"></textarea>
                  </div>
                </div>

                <div class="layui-form-item">
                  <div class="layui-input-block">
                    <button class="layui-btn" id="audit" data-val="${id}" lay-submit lay-filter="formDemo">保存</button>
                    <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
                  </div>
                </div>
              </form>`

  });

  renderForm();
})

$('html').on("click", "#audit", async function (e) {
  e.preventDefault();
  const DecorateId = $(e.target).data("val");
  const acceptancePeople = $('[name=auditPeople]').val();
  const acceptanceType = $('[name=auditType]').val();
  const acceptanceData = $('[name=auditContent]').val();
  const approver = localStorage.user;
  const type = 1;
  await ajax({ url: "Decorate/update", type: "post", data: { DecorateId, approver, type } });
  await ajax({ url: "Acceptance/add", type: "post", data: { acceptancePeople, acceptanceType, acceptanceData, DecorateId } });
  let limit = decorateObj.limit;
  let page = decorateObj.page;
  getContentShow(limit, page);
})


$("#decoratesearch").click(async function (e) {
  e.preventDefault();
  var value = $("[name=decorateVal]").val();
  var limit = 4;
  var page = 1;
  const { getCount, getAll } = await ajax({ url: "Decorate/getAll", type: "get", data: { limit, page, value } });

  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage
      , layer = layui.layer;
    //完整功能
    laypage.render({
      elem: 'demo4'
      , count: getAll.length
      , limit: 2
      , limits: [5, 10, 15]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
      , jump: async function (obj) {
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        page = obj.curr;
        limit = obj.limit;
        value = $("[name=decorateVal]").val();
        // console.log(value);
        const res = await ajax({ url: "Decorate/getAll", type: "get", data: { limit, page, value } });
        getContentShow(limit, page);
      }
    });
  });
})


$("html").on("click", "#decoupdate", async function (e) {
  e.preventDefault();
  const id = $(e.target).data("val");
  const { code, data } = await ajax({ url: "Community/getList", type: "post" });
  const res = await ajax({ url: "Buildings/getAll", type: "post" });
  const resUnit = await ajax({ url: "Unit/getAll", type: "post" });
  const RoomNum = await ajax({ url: "RoomNum/getAll", type: "post" });
  const resCommunity = await ajax({ url: "Community/getList", type: "post" });
  const { data: [{
    CommunityId, buildingsId, unitId, RoomNumId, applicant, applicantPhone, ConstructionUnit, head, headPhone, hearStarttime, headEndtime, DecorateId, noteContent
  }] } = await ajax({ url: "Decorate/getOne", type: "post", data: { id } })



  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['650px', '600px'], //宽高
    content: `<form class="layui-form" action="" >
                <div className="layui-form-item">
                  <h1>装修申请</h1>
                </div>
                <div class="layui-form-item">
                <label class="layui-form-label">小区</label>
                <div class="layui-input-block">
                  <select name="communityProjectsUpdate" lay-filter="aihao">
                  </select>
                </div>
              </div>
               

                <div class="layui-form-item">
                <label class="layui-form-label">楼栋</label>
                <div class="layui-input-block">
                  <select name="buildingChargingProjectsUpdate" lay-filter="aihao">
                  </select>
                </div>
              </div>
              <div class="layui-form-item">
              <label class="layui-form-label">单元</label>
              <div class="layui-input-block">
                <select name="unitIdChargingProjectsUpdate" lay-filter="aihao">
                </select>
              </div>
            </div>

            <div class="layui-form-item">
            <label class="layui-form-label">门牌号</label>
            <div class="layui-input-block">
              <select name="RoomNumIdChargingProjectsUpdate" lay-filter="aihao">
              </select>
            </div>
          </div>

              <div class="layui-form-item">
              <label class="layui-form-label">申请人</label>
              <div class="layui-input-inline">
                <input type="text" name="applicantUpdate" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
              <label class="layui-form-label">申请人电话</label>
              <div class="layui-input-inline">
                <input type="text" name="applicantPhoneUpdate" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
            </div>
            
            <div class="layui-form-item">
              <label class="layui-form-label">施工单位</label>
              <div class="layui-input-block">
                <input type="text" name="ConstructionUnitUpdate" autocomplete="off" placeholder="请输入" class="layui-input">
              </div>
            </div>

            <div class="layui-form-item">
            <label class="layui-form-label">负责人</label>
            <div class="layui-input-inline">
              <input type="text" name="headUpdate" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label">联系电话</label>
            <div class="layui-input-inline">
              <input type="text" name="headPhoneUpdate" required lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>


          <div class="layui-inline">
          <label class="layui-form-label">施工开始时间</label>
          <div class="layui-input-inline">
              <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test4" name="hearStarttimeUpdate" autocomplete="off" class="layui-input">
          </div>
        </div>
        <div class="layui-inline">
        <label class="layui-form-label" id="timeover">竣工结束时间</label>
        <div class="layui-input-inline">
            <input type="text" class="layui-input" placeholder="yy-mm-dd" id="test4" name="headEndtimeUpdate" autocomplete="off" class="layui-input">
        </div>
      </div>
          
          <div class="layui-form-item layui-form-text">
              <label class="layui-form-label">收费标准</label>
                <div class="layui-input-block">
                <button type="button" name="DecorateIdUpdate" class="layui-btn layui-btn-normal" id="DecorateIdUpdate">添加</button>
                  </div>
            </div>
           
            <table class="layui-table">
                  <colgroup>
                    <col width="100">
                    <col width="100">
                    <col>
                  </colgroup>
                  <thead>
                    <tr>
                      <th>收费项目</th>
                      <th>收费标准名称</th>
                      <th>项目类别</th>
                      <th>金额计算方式</th>
                      <th>单价</th>
                      <th>计量方式</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody id="standard-contentUpdate">

                  </tbody>
          </table>
            

          <div class="layui-form-item layui-form-text">
              <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="noteContentUpdate" placeholder="请输入内容" class="layui-textarea text-small"></textarea>
                  </div>
            </div>
              
                 

            <div class="layui-form-item">
            <div class="layui-input-block">
              <button class="layui-btn" id="DecorateBtnUpdate" data-val="${id}"  lay-submit lay-filter="formDemo">保存</button>
              <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
            </div>
          </div>
              
          </form>`

  });
  console.log(data);
  showOption(data, "[name=communityProjectsUpdate]");
  showOption(res.data, "[name=buildingChargingProjectsUpdate]");
  showOption(resUnit.dataAll, "[name=unitIdChargingProjectsUpdate]");
  showOption(RoomNum.dataAll, "[name=RoomNumIdChargingProjectsUpdate]");
  $("[name=communityProjectsUpdate]").find(`option[value=${CommunityId._id}]`).attr("selected", true);
  $("[name=buildingChargingProjectsUpdate]").find(`option[value=${buildingsId._id}]`).attr("selected", true);
  $("[name=unitIdChargingProjectsUpdate]").find(`option[value=${unitId._id}]`).attr("selected", true);
  $("[name=RoomNumIdChargingProjectsUpdate]").find(`option[value=${RoomNumId._id}]`).attr("selected", true);
  $("[name=applicantUpdate]").val(applicant);
  $("[name=applicantPhoneUpdate]").val(applicantPhone);
  $("[name=ConstructionUnitUpdate]").val(ConstructionUnit);
  $("[name=headUpdate]").val(head);
  $("[name=headPhoneUpdate]").val(headPhone);
  $("[name=hearStarttimeUpdate]").val(hearStarttime);
  $("[name=headEndtimeUpdate]").val(headEndtime);
  $("[name=noteContentUpdate]").val(noteContent);
  const DecorateIdRes = await $.ajax({
    url: "http://192.168.13.6:8000/ChargingProjects/getFind",
    type: "post",
    contentType: "application/json",
    data: JSON.stringify({ DecorateId }),
    success(res) {
      console.log(res);
      if (res.code) {
        console.log(res.data)
        const updateTrs = res.data.map(item => (
          `
            <tr data-val="${item._id}">
                  <td>${item.name}</td>
                  <td>${item.standard}</td>
                  <td>${item.type}</td>
                  <td>${item.price}</td>
                  <td>${item.calculation}</td>
                  <td>${item.measurement}</td>
                  <td>
                  <button type="button" class="layui-btn layui-btn-primary"  data-val="${item._id}" id="update-del">删除</button>
                  </td>
            </tr>
          `
        )).join('');

        $("#standard-contentUpdate").html(updateTrs)
      }
    }
  });
  // console.log(CommunityId)
  layui.use('laydate', function () {
    var laydate = layui.laydate;
    //执行一个laydate实例
    laydate.render({
      elem: '#test4' //指定元素
    });
  });
  renderForm();
})




$("html").on("click", "#DecorateIdUpdate", function (e) {
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['1000px', '600px'], //宽高
    content: `
              <table class="layui-hide" id="test" >
                  <colgroup>
                  <col width="150">
                  <col width="200">
                  <col>
                </colgroup>
                <thead>
                  <tr>
                    <th>收费项目</th>
                    <th>收费标准名称</th>
                    <th>项目类别</th>
                    <th>金额计算方式</th>
                    <th>单价</th>
                    <th>计量方式</th>
                    <th>状态</th>
                  </tr>
                </thead>
                <tbody id="ChargingProjects-content">
                </tbody>
            </table> 
           <div class="inner">
                  <button class="layui-btn  layui-layer-close layui-layer-close1" id="DecorateIdUpdateBtn" lay-submit lay-filter="formDemo">确定</button>
                  <button  class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</button>
           </div>
    `
  });

  layui.use('table', function () {
    var table = layui.table;
    table.render({
      elem: '#test'
      , url: "http://localhost:8000/ChargingProjects/getAll"
      , id: 'queryList'
      , cols: [[
        { type: 'checkbox' }
        , { field: 'name', width: 150, title: '收费项目', sort: true }
        , { field: 'standard', width: 150, title: '收费标准名称' }
        , { field: 'type', width: 150, title: '项目类别', sort: true }
        , { field: 'calculation', width: 150, title: '金额计算方式' }
        , { field: 'price', title: '单价', minWidth: 100 }
        , { field: 'measurement', width: 150, title: '计量方式', sort: true }
      ]]
      , parseData: function (res) { //res 即为原始返回的数据
        // $("html #ChargingProjects").html(trs);
        return {
          "code": res.code, //解析接口状态
          "msg": res.message, //解析提示文本
          "data": res.data //解析数据列表
        };
      }
      , done: function (res, page, count) {
        //可以自行添加判断的条件是否选中
        //这句才是真正选中，通过设置关键字LAY_CHECKED为true选中，这里只对第一行选中
        if (arr[0] == "all") {
          $('th[data-field=' + 0 + '] input[type="checkbox"]').prop('checked', true);
          $('th[data-field=' + 0 + '] input[type="checkbox"]').next().addClass('layui-form-checked');
          $('tr[data-index] input[type="checkbox"]').prop('checked', true);
          $('tr[data-index] input[type="checkbox"]').next().addClass('layui-form-checked');
        } else {

          for (var i = 0; i < arr.length; i++) {

            $('tr[data-index=' + arr[i] + '] input[type="checkbox"]').prop('checked', true);
            $('tr[data-index=' + arr[i] + '] input[type="checkbox"]').next().addClass('layui-form-checked');
          }
        }
      }
    });



    // renderForm();
    table.on('checkbox', function (obj) {
      // console.log(obj.checked); //当前是否选中状态
      // // console.log(obj.data); //选中行的相关数据
      // console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
      if (obj.type == "all" && obj.checked) {
        arr.length = 0;
        arr.push("all");
      } else if (obj.type == "one" && obj.checked) {
        if (arr[0] == "all") {
          arr.length = 0;
          arr.push(obj.tr.attr("data-index"))
        } else {
          arr.push(obj.tr.attr("data-index"))
        }
      } else if (obj.type == "one" && !obj.checked) {
        arr.splice(arr.indexOf(obj.tr.attr("data-index")), 1);
      } else if (obj.type == "all" && !obj.checked) {
        arr.length = 0;
      }
    });
  });
})
function getQueryUpdate(selectData, res) {
  const trs = selectData.map(item => (
    `
      <tr data-val="${item._id}">
          <td>${item.name}</td>
          <td>${item.standard}</td>
          <td>${item.type}</td>
          <td>${item.calculation}</td>
          <td>${item.price}</td>
          <td>${item.measurement}</td>
          <td>
              <button data-val="${item._id}" class="layui-btn layui-btn-primary" id="update-del">删除</button>
          </td>
      </tr>
    `
  )).join('');
  $(res).html(trs);
}

$('html').on("click", "#DecorateIdUpdateBtn", function (e) {

  selectData = layui.table.checkStatus('queryList').data;
  console.log(selectData)
  let res = "#standard-contentUpdate";
  getQueryUpdate(selectData, res);
})

//装修管理编辑
$("html").on("click", "#DecorateBtnUpdate", function (e) {
  e.preventDefault();

  const id = $(e.target).data("val");
  const CommunityId = $("[name=communityProjectsUpdate]").val();
  const buildingsId = $("[name=buildingChargingProjectsUpdate]").val();
  const unitId = $("[name=unitIdChargingProjectsUpdate]").val();
  const RoomNumId = $("[name=RoomNumIdChargingProjectsUpdate]").val();
  const applicant = $("[name=applicantUpdate]").val();
  const applicantPhone = $("[name=applicantPhoneUpdate]").val();
  const ConstructionUnit = $("[name=ConstructionUnitUpdate]").val();
  const head = $("[name=headUpdate]").val();
  const headPhone = $("[name=headPhoneUpdate]").val();
  const hearStarttime = $("[name=hearStarttimeUpdate]").val();
  const headEndtime = $("[name=headEndtimeUpdate]").val();
  const noteContent = $("[name=noteContentUpdate]").val();
  // DecorateId =  $("#standard-content tr").data("val");
  // console.log(noteContent)
  // if(DecorateId.length > 0){
  //   DecorateId.length = 0;
  // }
  for (var i = 0; i < $("#standard-contentUpdate tr").length; i++) {
    DecorateId.push($("#standard-contentUpdate tr").eq(i).data("val"));
  }
  var arr = [];
  for (var i = 0; i < DecorateId.length; i++) {
    for (var k = 0; k < del.length; k++) {
      if (DecorateId[i] == del[k]) {
        DecorateId.splice(i, 1);
      }
    }
  }
  console.log(DecorateId);
  //  console.log(DecorateId);
  $.ajax({
    url: "http://192.168.13.6:8000/Decorate/updateOne",
    type: "post",
    data: {
      id, CommunityId, buildingsId, unitId, RoomNumId, applicant, applicantPhone, ConstructionUnit, head, headPhone, hearStarttime, headEndtime, noteContent, DecorateId
    },
    traditional: true,
    success(res) {
      if (res.code) {
        alert(res.message);
        let limit = decorateObj.limit;
        let page = decorateObj.page;
        getContentShow(limit, page);
      }
    }
  })
})

//点击编辑删除
$('html').on("click", "#update-del", function (e) {
  del.length = 0;
  e.preventDefault();
  const id = $(e.target).data("val");
  del.push(id);
  // console.log(DecorateId);
  $(e.target).parents("tr").hide();
})

$("html").on("click", "#decodel", async function (e) {
  const id = $(e.target).data("val");

  const { code, message } = await ajax({ url: "Decorate/del", type: "post", data: { id } });
  if (code) {
    alert(message);
    indexShow();
  }
})


$("html").on("click", ".SMSAdd", function (e) {
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['650px', '600px'], //宽高
    content: `<form class="layui-form" action="" >
                <div className="layui-form-item">
                  <h1>添加短信模板</h1>
                </div>

                <div class="layui-form-item">
                <label class="layui-form-label">短信标题</label>
                <div class="layui-input-inline">
                  <input type="text" name="title" autocomplete="off" placeholder="请输入" class="layui-input">
                </div>
              </div>

                <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">短信内容</label>
                  <div class="layui-input-block">
                      <textarea name="content" placeholder="请输入内容" class="layui-textarea text-small"></textarea>
                    </div>
              </div>

              
            
            <div class="layui-form-item">
              <label class="layui-form-label">签名</label>
              <div class="layui-input-inline">
                <input type="text" name="sign" autocomplete="off" placeholder="请输入" class="layui-input">
              </div>
            </div>

   
            <div class="layui-form-item">
            <div class="layui-input-block">
              <button class="layui-btn" id="smsTemplateAdd"  lay-submit lay-filter="formDemo">保存</button>
              <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
            </div>
          </div>
              
          </form>`

  });
})
$("#SMS").click(async function () {
  const { code, message, data } = await ajax({ url: "SMS/getAll", type: "post" });
  const opt = data.map(item => (
    `
      <option value="${item._id}">${item.content}</option>
    `
  )).join('');
  $('[name=MessageTemplate]').html(opt);
  renderForm();
})

async function smsShow() {
  const { code, message, data } = await ajax({ url: "SMS/getAll", type: "post" });
  const trs = data.map(item => (
    `
      <tr>
          <td>${item.title}</td>
          <td>${item.content}</td>
          <td>${item.sign}</td>
          <td>审核通过</td>
          <td>
              <button class="layui-btn layui-btn-primary" data-val="${item._id}" id="updateSMS">编辑</button>
              <button class="layui-btn layui-btn-primary" data-val="${item._id}" id="smsDel">删除</button>
          </td>
      </tr>
    `
  )).join('');
  $("#sms-content").html(trs)
  console.log(data)
}
$("#template").click(function () {
  smsShow();
})


$("html").on("click", "#smsTemplateAdd", async function (e) {
  e.preventDefault();
  const title = $("[name=title]").val();
  const content = $("[name=content]").val();
  const sign = $("[name=sign]").val();
  const { code, message } = await ajax({ url: "SMS/add", type: "post", data: { title, content, sign } })
  if (code) {
    alert(message);
    smsShow();
  }
})

$("html").on("click", "#updateSMS", async function (e) {
  const id = $(e.target).data("val");
  const { code, data: [{ title, content, sign, _id }] } = await ajax({ url: "SMS/findOne", type: "post", data: { id } });
  // console.log(res)
  layer.open({
    type: 1,
    skin: 'layui-layer-rim', //加上边框
    area: ['650px', '600px'], //宽高
    content: `<form class="layui-form" action="" >
                <div className="layui-form-item">
                  <h1>编辑短信模板</h1>
                </div>

                <div class="layui-form-item">
                <label class="layui-form-label">短信标题</label>
                <div class="layui-input-inline">
                  <input type="text" name="titleUpdate" autocomplete="off" placeholder="请输入" class="layui-input">
                </div>
              </div>

                <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">短信内容</label>
                  <div class="layui-input-block">
                      <textarea name="contentUpdate" placeholder="请输入内容" class="layui-textarea text-small"></textarea>
                    </div>
              </div>

              
            
            <div class="layui-form-item">
              <label class="layui-form-label">签名</label>
              <div class="layui-input-inline">
                <input type="text" name="signUpdate" autocomplete="off" placeholder="请输入" class="layui-input">
              </div>
            </div>

   
            <div class="layui-form-item">
            <div class="layui-input-block">
              <button class="layui-btn" id="templateEditor"  lay-submit lay-filter="formDemo">保存</button>
              <a   class="layui-btn layui-btn-primary layui-layer-close layui-layer-close1">返回</a>
            </div>
          </div>
              
          </form>`

  });
  // console.log(data);
  $("[name=titleUpdate]").val(title);
  $("[name=contentUpdate]").val(content);
  $("[name=signUpdate]").val(sign);
  $("#templateEditor").attr("data-val", _id);
})

$("html").on("click", "#templateEditor", async function (e) {
  e.preventDefault();
  const id = $(e.target).data("val");
  const title = $("[name=titleUpdate]").val();
  const content = $("[name=contentUpdate]").val();
  const sign = $("[name=signUpdate]").val();
  const { code, message } = await ajax({ url: "SMS/update", type: "post", data: { id, title, content, sign } });
  if (code) {
    alert(message);
    smsShow();
  }
})

$("#sendSms").click(async function (e) {
  e.preventDefault();
  const title = $('[name=MessageTemplate]').val();
  const addTime = getCurrentDate();
  const { code, message } = await ajax({ url: "SMSsend/add", type: "post", data: { title, addTime } });
  if (code) {
    alert(message)
  }
})

$("#mass").click(async function () {
  const { code, message, data } = await ajax({ url: "SMS/getAll", type: "post" });
  const opt = data.map(item => (
    `
      <option value="${item._id}">${item.content}</option>
    `
  )).join('');
  $('[name=MessageTemplate]').html(opt);
  renderForm();
})

$("html").on("click", "#smsDel", async function (e) {
  e.preventDefault();
  const id = $(e.target).data("val");
  const { code, message } = await ajax({ url: "SMS/delOne", type: "post", data: { id } });
  if (code) {
    alert(message);
    smsShow();
  }
})

$('#smsRecord').click(async function (e) {
  e.preventDefault();
  const { code, data } = await ajax({ url: "SMSsend/findAll", type: "post" });
  // console.log(data);
  const trs = data.map(item => (
    `
      <tr>
          <td>${item.title.content}</td>
          <td>${item.num}</td>
          <td>${item.addTime}</td>
      </tr>
    `
  )).join('');
  $("#smsrecord-content").html(trs)
})

$('#space15 .index').click(function (e) {
  let divs = $('#space15').children();
  for (var i = 0; i < divs.length; i++) {
    divs.eq(i).find(".active").removeClass("active");
  }
  $(e.target).parent().addClass("active");
  danjia = Number($(e.target).find(".s2").text());
  tiaoshu = Number($(e.target).find(".s1").text()) * 10000;
  let num = $("#number").val();
  $("#payNum").text(danjia * tiaoshu * num)
})

$("#jia").click(function (e) {
  $("#flex input").val(Number($("#flex input").val()) + 1);
  let num = $("#number").val();
  $("#payNum").text(danjia * tiaoshu * num)
})

$("#jian").click(function (e) {
  if ($("#flex input").val() > 1) {
    $("#flex input").val(Number($("#flex input").val()) - 1);
    let num = $("#number").val();
    $("#payNum").text(danjia * tiaoshu * num)
  }
})

$("#Buynow").click(async function (e) {
  e.preventDefault();
  let buyNum = $("#number").val();
  let payNum = $("#payNum").text();

  const type = "套餐类型";
  const num = (tiaoshu / 10000) + '万条';

  const cost = payNum;
  const addTime = getCurrentDate();
  console.log(danjia, tiaoshu, num);
  const { code, message } = await ajax({ url: "SMSBuy/add", type: "post", data: { type, num, buyNum, cost, addTime } });
  if (code) {
    alert(message)
  }
})

$("#sms-list").click(async function (e) {
  const { code, data: { findAll } } = await ajax({ url: "SMSBuy/findAll", type: "post" });
  if (code) {
    console.log(data);
    const trs = findAll.map(item => (
      `
        <tr>
            <td>${item.addTime}</td>
            <td>${item.type}</td>
            <td>${item.num}</td>
            <td>${item.buyNum}</td>
            <td>${item.cost}</td>
        </tr>
      `
    )).join('');
    $("#sms-comtent-buy").html(trs)
  }
})